package com.qf.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component  // 作用与 service，repository，controller和restcontroller 类似
public class TokenInterceptor implements HandlerInterceptor {
    // 这个方法会在controller之前被调用
    // 返回true，代表本次请求会继续给到后面的controller
    // 返回false，本次请求到此为止，不会在调用后面的controller了
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器拦截到了请求，url为:" + request.getRequestURL());
        String token = request.getParameter("token");
        System.out.println("拦截器拦截到的请求中的参数token=" + token);

        if (token == null || "".equals(token)) {
            throw new RuntimeException("token为空了");
        }
        // 对token的合法性进行校验
        if (!token.equals("123456")) {
            throw new RuntimeException("token不合法");
        }

        return true;
    }
}
